import json

from zhipuai import ZhipuAI

from app.business.model_config import get_model_config
from app.initializer import init_config


# def get_zhipu_ai(message):
#     if message is None or message == "":
#         return "请输入不为空内容"
#     history_data = []
#     history_data.append({"role": "user", "content": message}, )
#     client = ZhipuAI(api_key="1e6b5acd67bc40acba6c689ef0543b60.Qby5oXHwnD8X1GlB")  # 填写您自己的APIKey
#     response = client.chat.completions.create(
#         model="glm-4",  # 填写需要调用的模型名称
#         messages=history_data,
#     )
#     answer = response.choices[0].message.content.strip()
#     print(answer)
#     return str(answer)


def chat_zhipu_ai(message, history_formatted):
    if message is None or message == "":
        return "请输入不为空内容"
    print("chat_zhipu_ai")
    history_data = []
    if history_formatted is not None:
        for i, old_chat in enumerate(history_formatted):
            if old_chat['role'] == "user":
                history_data.append(
                    {"role": "user", "content": old_chat['content']}, )
            elif old_chat['role'] == "AI" or old_chat['role'] == 'assistant':
                history_data.append(
                    {"role": "assistant", "content": old_chat['content']}, )
    history_data.append(
        {"role": "system", "content": "你是一个乐于解答各种问题的助手，你的任务是为用户提供专业、准确、有见地的建议。"}, )
    history_data.append({"role": "user", "content": message}, )
    print(message)
    zhipu_api_key = get_model_config(model_name="zhipu").model_api_key
    client = ZhipuAI(api_key=zhipu_api_key)  # 填写您自己的APIKey
    try:
        response = client.chat.completions.create(
            model="glm-4-plus",  # 填写需要调用的模型名称
            messages=history_data,
        )
        answer = response.choices[0].message.content.strip()
    except Exception as e:
        answer = message

    print(answer)
    return str(answer)


def chat_zhipu_ai_images(img_path):
    import base64
    from zhipuai import ZhipuAI

    with open(img_path, 'rb') as img_file:
        img_base = base64.b64encode(img_file.read()).decode('utf-8')
    zhipu_api_key = get_model_config(model_name="zhipu").model_api_key
    client = ZhipuAI(api_key=zhipu_api_key)  # 填写您自己的APIKey
    try:
        response = client.chat.completions.create(
            model="glm-4v-plus-0111",  # 填写需要调用的模型名称
            messages=[
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": img_base
                            }
                        },
                        {

                            "type": "text",
                            "text": "你是图片整理大师。现在给你了一张图片，区别是纯图像的图片还是文字类的图片还是图像加文字的图片，理解是否需要对图片中文字提取，"
                                    "要求：1.如果是一张纯图片里面只有一部分可有可无的文字主要理解还是图片内容或则是水印截图等文字内容很少大多都是图片信息,不需要对图片内容描述 则返回json格式为{\"text\":'是'}。"
                                    "2.如果图片内容是文字描述， 只返回里面的文字内容。只返回识别的文字内容不要返回其他描述"
                                    "3.图片是纯文字类的图片只返回里面文字以json格式返回json格式为{\"text\":'图片内文字内容'}"
                                    "4.返回内容要么是 {\"text\":'图片内文字内容'} 要么是{\"text\":'是'} "
                        }
                    ]
                }
            ]
        )
        re =extract_text_value(response.choices[0].message.content)
    except Exception as e:
        re = img_path
    return re


def extract_text_value(json_str):
    """
    将 JSON 格式的字符串转为字典并提取 text 值
    如果转换失败或不存在 text 键，则返回原字符串

    :param json_str: JSON 格式的字符串
    :return: text 值或原字符串
    """
    try:
        print(json_str)
        data = json.loads(json_str, strict=False)
        if isinstance(data, dict) and 'text' in data:
            return data['text']


    except (json.JSONDecodeError, AttributeError, TypeError):
        pass
    return json_str

# chat_zhipu_ai_images("C:\\Users\\Administrator\\Desktop\\高校兼职\\images\\图片1.png")
